<template>
  <div class="portalDiv">
    <div class="portalTop">
      <div>
        <div class="Div1">
          <ImgUpload :author-id="authorId" @success="success" v-if="isCurrent">
            <img v-if="info.imgUrl !== null" :src="info.imgUrl"
                 alt="">
            <img v-else src="../assets/default.jpeg" alt="">
          </ImgUpload>
          <img v-else-if="info.imgUrl !== null" :src="info.imgUrl"
               alt="">
          <img v-else src="../assets/default.jpeg" alt="">
        </div>
        <div class="Div2">
          <h1>{{info.name}}</h1>
          <el-tag type="warning"
                  v-if="info.affiliation !== null"
          >{{info.affiliation}}</el-tag>
        </div>
        <div class="Div3">
          <div>发文数
            <span style="color: #e7e7e7; font-size: 10px">- - ————————————— </span>
            {{info.paperCount}} </div>
          <div>引文数
            <span style="color: #e7e7e7; font-size: 10px">- - ————————————— </span>
            {{info.citationCount}}</div>
          <el-button type="primary"
                     class="favor_button"
                     @click="favor_change"
                     :style="{backgroundColor:favor.bg_color, color: favor.ft_color}"
                     @mouseenter="favor_moused()" @mouseleave="favor_cancel()">
            {{favor.content}}</el-button>
        </div>
      </div>

    </div>

    <div class="portalMedium">
      <el-divider></el-divider>
      <el-menu
          :default-active="activeIndex"
          class="el-menu"
          mode="horizontal"
          @select="handleSelect"
      >
        <el-menu-item index="1">基本信息</el-menu-item>
        <el-menu-item index="2">学术成果</el-menu-item>
        <el-menu-item index="3" v-if="isCurrent">申请列表</el-menu-item>
      </el-menu>
      <el-button type="primary" icon="el-icon-circle-plus"
                 v-if="isCurrent"
                 @click="addPaper()"
                 style="float: right; margin: 5px 0 0 20px">
        添加新的学术成果</el-button>
    </div>

    <div class="portalMain">
      <div class="listDiv">
        <div id="info" class="infoDiv"
             :style="{ boxShadow: `var(--el-box-shadow-light)`}">
          <br/><span>学者基本信息</span>
          <Editor :authorId="authorId" :isCurrent="isCurrent"></Editor>
        </div>

        <div id="paper" class="paperDiv"
             :style="{ boxShadow: `var(--el-box-shadow-light)`}">
          <br/><span>全部成果</span>
          <el-divider></el-divider>
          <div v-if="papers.length <= 0"
               style="text-align: center; padding-top: 20px; color: #8c939d">
              <h2>暂无数据</h2>
          </div>
          <div v-else
               v-for="(item, i) in showPapers"
               class="paperDiv1">
            <div>
              <h4 class="h4" @click="jumpToPaper(item)">{{item.title}}</h4>
              <div style="float: right; color: #72767b; font-size: 13px">{{item.date}}</div>
            </div>
            <br/>
            <div style="margin-top: 12px">
              <el-avatar :size="22" :src="circleUrl" style="float: left; margin: 0"></el-avatar>
              <div style="float: left; padding-left: 5px">{{getAuthorList(item)}}</div>

              <div style="float: right" v-if="isCurrent">
                <el-button type="text" @click="deletePaper(item)">删除</el-button>
                <el-button type="text" @click="updatePaper(item)">修改</el-button>
              </div>
            </div>
            <el-divider></el-divider>
          </div>
          <el-pagination background
                         style="text-align: center; padding-bottom: 10px"
                         v-if="papers.length > 10"
                         @current-change="handleCurrentChange"
                         layout="prev, pager, next"
                         :current-page="currentPage"
                         :page-size="10"
                         :total="totalNum_1">
          </el-pagination>
        </div>

        <div id="apply" class="applyDiv"
             v-if="isCurrent"
             :style="{ boxShadow: `var(--el-box-shadow-light)`}">
          <br/><span>申请列表</span>
          <el-divider></el-divider>
          <div v-if="applyList.length <= 0"
               style="text-align: center; padding-top: 20px; color: #8c939d">
            <h2>暂无数据</h2>
          </div>
          <div v-else
               v-for="(item, i) in showApplies"
               class="paperDiv1">
            <div>
              <h4>{{item.title}}</h4>
              <div style="float: right; color: #72767b; font-size: 13px">{{item.applyDate}}</div>
            </div>
            <div style="margin-top: 20px">
              <el-avatar :size="22" :src="circleUrl" style="float: left; margin: 0"></el-avatar>
              <div style="float: left; padding-left: 5px">{{info.name}}</div>
              <el-tag style="float: left;margin: -3px 8px">{{item.type}}</el-tag>
              
              
                <el-tag style="float: left;margin: -3px 8px" type="info" v-if="item.isPermitted===null">待审核</el-tag>
                <el-tag style="float: left;margin: -3px 8px" type="success" v-else-if="item.isPermitted===true">已通过</el-tag>
                <el-tag style="float: left;margin: -3px 8px" type="danger" v-else-if="item.isPermitted==false">未通过</el-tag>
              

              <div style="float: right" v-if="isCurrent">
                <el-button type="text"
                           @click="openApplyItem(item.applyId)">申请详情</el-button>
                <el-button type="text"
                           icon="el-icon-edit"
                           @click="cancelApply(item,i)">撤销申请</el-button>
              </div>
              <div style="clear: both"></div>
            </div>
            <el-divider></el-divider>
          </div>
          <el-pagination background
                         style="text-align: center; padding-bottom: 10px"
                         v-if="applyList.length > 10"
                         @current-change="handleCurrentChange_2"
                         layout="prev, pager, next"
                         :current-page="currentPage_2"
                         :page-size="10"
                         :total="totalNum_2">
          </el-pagination>
        </div>
      </div>

      <div class="claimDiv">
        <div class="buttonDiv"
             :style="{ boxShadow: `var(--el-box-shadow-light)`}">
          <h5 style="padding-top: 8px">实名认领</h5>
          <el-divider></el-divider>
          <div class="claimDiv2">
            点击进行人员认领 <br/>
            认领成功后可获取权限 <br/>
            <el-button type="info" disabled v-if="info.userId !== null && !isCurrent">已被认领</el-button>
            <el-button type="primary" plain disabled v-if="info.userId !== null && isCurrent">已认领</el-button>
            <el-button type="info" disabled v-if="info.userId === null && isClaimed">点击认领</el-button>
            <el-button type="primary" size="medium"
                       v-if="info.userId === null && !isClaimed" @click="claimBtn">实名认领</el-button>
          </div>
        </div>

        <div class="netDiv"
             :style="{ boxShadow: `var(--el-box-shadow-light)`}">
          <h5 style="padding-top: 8px">学者关系网络</h5>
          <el-divider></el-divider>
          <RelationNet :authorId="authorId" :authorName="info.name"></RelationNet>
        </div>
      </div>
    </div>

    <el-backtop target=".portalDiv">
      <i class="el-icon-caret-top"></i>
    </el-backtop>

    <el-dialog
        v-model="dialogVisible"
        title="实名认证"
        width="30%"
        :before-close="handleClose">

      <el-form>
        <el-form-item label="工作邮箱" label-width="80px">
          <el-input v-model="submit_info.email"></el-input>
        </el-form-item>
        <el-form-item label="验证码" label-width="80px">
          <el-input v-model="submit_info.identification">
            <template #append>
              <el-button size="medium"
                         @click="sendNumber(submit_info.email)">{{content}}
              </el-button>
            </template>
          </el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button size="small" @click="handleClose">取消</el-button>
          <el-button size="small" type="primary" @click="submitClaim"
          >提交</el-button
          >
        </span>
      </template>
    </el-dialog>

    <el-dialog
        v-model="deleteDialogVisible"
        title="申请详情"
        width="60%"
        custom-class="el-dialog-s"
        :before-close="cancel">

      <div style="padding: 10px;height: 390px; overflow: auto">
        <el-table :data="tableData"
                  :show-header="false"
                  :cell-style="columnStyle"
                  border>
          <el-table-column prop="name" style="width: 40%" />
          <el-table-column prop="value" style="width: 60%" />
        </el-table>

        <el-divider></el-divider>
        <div style="display: inline">
          <h3 style="float:left;">备注</h3>
          <div v-if="currentType === 'delete'"
               style="font-size: 12px; padding-top: 22px">（必填）</div>
        </div>

        <el-input
            v-model="currentOther"
            :rows="2"
            placeholder="请输入申请理由"
            type="textarea"></el-input>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button size="small" @click="cancel">取消</el-button>
          <el-button size="small" type="primary" @click="submitApply">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
  
  <ApplyInfo ref="applyInfo"></ApplyInfo>
</template>

<script>
import axios from "@/utils/MyAxios"
import qs from "qs"
import { Plus } from '@element-plus/icons'
import {ElMessage, ElMessageBox} from "element-plus";
import RelationNet from './RelationNet'
import Editor from './wangEditor'
import ImgUpload from '../../components/ImgUpload'
import ApplyInfo from "./ApplyInfo";
export default {
  name: "Portal_new",
  components: {
    RelationNet, Editor, Plus, ImgUpload,ApplyInfo
  },
  props: {
    authorId: Number,
  },
  data() {
    return {
      token: '',
      isLogin: false,
      isCurrent: false,
      isClaimed: false,

      info: {
        userId: null,
      },
      affiliation: '',
      circleUrl: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
      favor: {
        isFollowed: false,
        content: '点击关注',
        bg_color: '#1E90FF',
        ft_color: '#ffffff',
      },
      papers: [],
      showPapers: [],
      totalNum_1: 100,
      applyList: [],
      showApplies: [],
      totalNum_2: 100,

      currentItem: { paperId: '' },
      currentType: '',
      currentOther: '',
      currentData: {
        doi: '',
        docType: '',
        title: '',
        abstract_: '',
        date: '',
      },
      currentPage: 1,
      currentPage_2: 1,

      activeIndex: "1",
      dialogVisible: false,
      success: '',
      content: '发送验证码',
      submit_info: {
        email: '',
        identification: ''
      },

      tableData: [],
      deleteDialogVisible: false,
    }
  },
  created() {
    this.token = localStorage.getItem("token");
    this.isLogin = this.token!==null;
    this.checkToken();
    this.authorCheck();
    this.getDoorInfo();
    this.getAuthorInfo();
    this.getAuthorPaper();
    this.getApplyList();
  },
  methods: {
    openApplyItem(applyId){
      this.$refs.applyInfo.openInfo(applyId);
    },
    checkToken() {
      let token = localStorage.getItem("token");
      if(token === null){
        this.isLogin = false;
      } else {
        let data = { token }
        axios.post("/api/user/token",qs.stringify(
          data
        )).then(res=>{
          console.log(res);
          data = res.data;
          this.isLogin = data.code === 0;
        })
      }
    },
    checkLogin() {
      // console.log(this.isLogin);
      if (!this.isLogin) {
        // localStorage.removeItem("token")
        // localStorage.removeItem("user")
        ElMessage.warning("请先登录")
        window.open("/user/sign/login","_self");
        return false;
      }
      return true;
    },

    getAuthorInfo() {
      console.log('获取学者详情');
      axios.post('/api/author/info', qs.stringify({
        authorId: this.authorId,
      })).then(res => {
        console.log(res);
        if (res.data.code === 0)
          this.info = res.data.data;
      }).catch(err => {
        console.log(err);
      })
    },
    getDoorInfo() {
      axios.post('/api/door/info', qs.stringify({
        authorId: this.authorId
      })).then(res => {
        console.log(res);
        if (res.data.code === 0) {
          this.info.userId = res.data.data.userId;
        }
      })
    },
    getApplyList() {
      if (this.isLogin) {
        axios.post('/api/apply/list', qs.stringify({
          token: this.token,
        })).then(res => {
          console.log(res);
          if (res.data.code === 0) {
            this.applyList = res.data.data;
            if (this.applyList.length <= 10)
              this.showApplies = this.applyList;
            else {
              this.showApplies = this.applyList.slice(0, 10);
              this.totalNum_2 = (this.applyList.length / 10) + 1
            }
          } else
            this.applyList = [];
        })
      }
    },
    getAuthorPaper() {
      console.log('获取学者文献列表');
      axios.post('/api/author/paper', qs.stringify({
        authorId: this.authorId,
      })).then(res => {
        console.log(res);
        if (res.data.code === 0) {
          this.papers = res.data.data;
          if (this.papers.length <= 10)
            this.showPapers = this.papers;
          else {
            this.showPapers = this.papers.slice(0, 10);
            this.totalNum_1 = (this.papers.length / 10) + 1
          }
        }
      }).catch(err => {
        console.log(err);
      })
    },
    getAuthorList(item) {
      let authors = item.authors.slice(0, 3);
      let end = '';
      if (item.authors.length > 3) {
        end = '...';
      }
      return authors.toString() + end;
    },
    authorCheck() {
      console.log('当前用户是否关注该学者');
      axios.post('/api/author/check', qs.stringify({
        token: this.token,
        authorId: this.authorId,
      })).then(res => {
        console.log(res);
        if (res.data.code === 0) {
          this.favor.isFollowed = res.data.data.isFollowed;
          if (this.favor.isFollowed)
            this.favor.content = '已关注';
          this.isClaimed = res.data.data.isClaimed;
          this.isCurrent = res.data.data.isCurrent;
        } else {
          console.log(res.data.msg);
          this.isCurrent = this.isClaimed = false;
        }
      }).catch(err => {
        console.log(err);
        this.isCurrent = this.isClaimed = false;
      })
    },

    change_color(color1, color2) {
      this.favor.bg_color = color1;
      this.favor.ft_color = color2;
    },
    favor_change() {
      this.checkLogin();
      if (!this.favor.isFollowed) {
        this.favor.content = '点击关注';
        this.change_color('#ffffff', '#1E90FF');
        this.followAdd();
      } else {
        this.favor.content = '已关注';
        this.change_color( '#1E90FF', '#ffffff');
        this.followCancel();
      }
    },
    followAdd() {
      console.log('关注')
      axios.post('/api/follow/add', qs.stringify({
        token: this.token,
        authorId: this.authorId,
      })).then(res => {
        if (res.data.code === 0) {
          console.log('关注成功');
          ElMessage.success('关注成功');
          this.favor.content = '已关注';
          this.favor.isFollowed = true;
        } else {
          ElMessage.error('关注失败，请重新尝试')
        }
      }).catch(err => {
        console.log(err);
      })
    },
    followCancel() {
      console.log('取消关注')
      axios.post('/api/follow/cancel', qs.stringify({
        token: this.token,
        authorId: this.authorId,
      })).then(res => {
        if (res.data.code === 0) {
          console.log('取消关注成功');
          ElMessage.warning('取消关注');
          this.favor.content = '点击关注';
          this.favor.isFollowed = false;
        } else {
          ElMessage.error('取消关注失败，请重新尝试')
        }
      }).catch(err => {
        console.log(err);
      })
    },
    favor_moused() {
      this.change_color( '#4169E1', '#ffffff');
    },
    favor_cancel() {
      if (this.favor.isFollowed)
        this.change_color('#ffffff', '#1E90FF');
      else
        this.change_color( '#1E90FF', '#ffffff');
    },

    handleSelect(key) {
      switch (key) {
        case "1": document.getElementById("info").scrollIntoView(); break;
        case "2": document.getElementById("paper").scrollIntoView(); break;
        case "3": document.getElementById("apply").scrollIntoView(); break;
      }
    },
    handleClose() {
      this.dialogVisible = false;
      this.submit_info = {};
    },

    checkEmail(email) {
      console.log('检查邮箱格式');
      let reg = /^\w+@[a-zA-Z0-9]{2,10}(?:\.[a-z]{2,4}){1,3}$/;
      //let reg = /[A-Za-z\\d]+([-_.][A-Za-z\\d]+)*@([A-Za-z\\d]+[-.])+[A-Za-z\\d]{2,4}/;
      let matches = reg.test(email);
      console.log(matches);
      return matches;
    },
    sendNumber(email) {
      if (this.checkEmail(email)) {
        console.log('发送验证码');
        axios.post('/api/user/sendCode', qs.stringify({
          email: email
        })).then(res => {
          if (res.data.code !== 0) {
            this.$message.error('发送失败，请检查邮箱是否正确');
          } else {
            this.content = '已发送';
            ElMessage.success("验证码发送成功")
          }
        }).catch(err => {
          console.log(err);
          this.$message.error('发送失败，请检查邮箱是否正确');
        })
      } else {
        this.$message.error('邮箱格式错误');
      }
    },
    submitClaim() {
      if (this.token === null || this.token === '')
        this.$message.error('请先登录');
      else if (this.submit_info.email === '')
        this.$message.error('请填写您的工作邮箱');
      else if(!this.checkEmail(this.submit_info.email))
        this.$message.error('邮箱格式错误');
      else if (this.submit_info.identification === '')
        this.$message.error('请填写验证码');
      else if (this.checkCode()) {
        this.claim();
        this.dialogVisible = false;
      } else
        this.$message.error('验证码错误！');
    },
    async checkCode() {
      console.log('验证邮箱验证码');
      try {
        let res = await this.check();
        return res.data.code !== 1;
      } catch (err) {
        console.log(err);
        return false;
      }
    },
    check() {
      return new Promise(resolve => {
        axios.post('/api/user/checkCode', qs.stringify({
          email: this.submit_info.email,
          code: this.submit_info.identification,
        })).then(res => {
          console.log(res.data.code !== 1);
          resolve(res);
        }).catch(err => {
          console.log(err);
        })
      })
    },
    claim() {
      console.log('提交认领门户申请');
      axios.post('/api/apply/claim', qs.stringify({
        token: this.token,
        email: this.submit_info.email,
        authorId: this.authorId,
      })).then(res => {
        if (res.data.code === 0) {
          console.log('提交成功!');
          this.$message.success('已提交！');
          this.isClaimed = true;
        }
      }).catch(err => {
        console.log(err);
      })
    },
    claimBtn() {
      if (this.isLogin)
        this.dialogVisible = true;
      else
        this.checkLogin();
    },

    deletePaper(item) {
      this.deleteDialogVisible = true;
      this.currentType = 'delete';
      this.currentItem = item;
      this.tableData = [{
        name: '作者',
        value: this.getAuthorList(item),
      },
        {
          name: '论文标题',
          value: item.title,
        },
        {
          name: '申请类型',
          value: '删除论文',
        },
        {
          name: '申请时间',
          value: this.getCurrentDate(),
        },
      ]
    },
    updatePaper(item) {
      const { href } = this.$router.resolve({
        path: '/apply/update',
        query: {
          authorId: this.authorId,
          paperId: item.paperId
        }
      })
      window.open(href, '_blank');
    },
    addPaper() {
      const { href } = this.$router.resolve({
        path: '/apply/add',
        query: {
          authorId: this.authorId
        }
      })
      window.open(href, '_blank');
    },

    getCurrentDate() {
      let date = new Date();
      let yy = date.getFullYear();
      let mm = date.getMonth() + 1;
      let dd = date.getDate();
      return yy + '-' + mm + '-' + dd;
    },
    cancel() {
      this.deleteDialogVisible = false;
      this.currentData = {};
    },
    submitApply() {
      if (this.currentOther === '')
        this.$message.error('备注不能为空！');
      else
        axios.post('/api/apply/manage', {
          token: this.token,
          paperId: this.currentItem.paperId,
          type: this.currentType,
          other: this.currentOther,
        }).then(res => {
          console.log(res);
          if (res.data.code === 0) {
            this.$message.success('提交成功！');
            this.deleteDialogVisible = false;
            this.currentItem = {};
            this.currentType = this.currentOther ='';
          }
        }).catch(err => {
          console.log(err);
          this.$message.error('提交失败，请再次尝试！');
        })
    },
    columnStyle({row, column, rowIndex, columnIndex}) {
      if (columnIndex === 0)
        return 'background: #f9f9f9';
      else
        return 'background: #ffffff';
    },

    cancelApply(item,index) {
      ElMessageBox.confirm(
          '是否确认撤销申请？',
          '是否确认',
          {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
          }
      ).then(()=>{
        axios.post('/api/apply/cancel', qs.stringify({
          applyId: item.applyId
        })).then(res => {
          console.log(res);
          if (res.data.code === 0){
            ElMessage.success('已撤销申请');
            this.applyList.splice(index,1);
          } else
            ElMessage.error('撤销失败，请重试！');
        }).catch(err => {
          console.log(err);
          ElMessage.error('撤销失败，请重试！');
        })
      })
      
    },
    jumpToPaper(item) {
      const { href } = this.$router.resolve({
        path: '/detail',
        query: {
          paperId: item.paperId
        }
      })
      window.open(href, '_blank');
    },
    handleCurrentChange(current) {
      this.currentPage = current;
      this.showPapers = this.papers.slice(10*(current-1), 10*current);
      document.getElementById("paper").scrollIntoView();
    },
    handleCurrentChange_2(current) {
      this.currentPage_2 = current;
      this.showApplies = this.applyList.slice(10*(current-1), 10*current);
      document.getElementById("apply").scrollIntoView();
    },
  }
}
</script>

<style scoped>
.portalDiv {
  margin-top: 20px;
  width: 100%;
  height: 100%;
}
.portalTop {
  width: 60%;
  height: 190px;
  margin: 0 auto;
}
.portalMedium {
  width: 60%;
  height: 100px;
  margin: 0 auto -34px;
}
.portalMain {
  margin: 0 -8px 0 -8px;
  width: 100%;
  position: absolute;
  background-color: #e7e7e7;
}
.Div1 {
  display: inline-block;
  float: left;
}
.Div1 img {
  margin: 10px;
  width: 180px;
  height: 180px;
  border-radius: 50%;
}
.Div2 {
  float: left;
  width: 25%;
  margin: 10px 0 0 20px;
}
.Div3 {
  float: right;
  margin: 5% 0;
  width: 35%;
  text-align: left;
}
.Div3 div {
  padding-top: 10px;
}
.favor_button {
  margin: 30px 0 0 10px;
  width: 94%;
}
.portalMedium >>> .el-divider {
  margin-bottom: 4px;
}
.el-menu {
  float: left;
}
.listDiv {
  width: 45%;
  min-height: 200px;
  float: left;
  margin: 20px 5px 0 15%;
}
.claimDiv {
  float: right;
  width: 22%;
  margin: 20px 16% 0 0;
}
.buttonDiv {
  background-color: white;
  margin-bottom: 20px;
}
.netDiv {
  height: 360px;
  background-color: white;
}
.infoDiv {
  min-height: 100px;
  background-color: white;
  margin-bottom: 20px;
}
.paperDiv {
  min-height: 200px;
  background-color: white;
  margin-bottom: 20px;
}
.applyDiv {
  min-height: 200px;
  background-color: white;
  margin-bottom: 20px;
}
.claimDiv h5 {
  font-size: 14px;
  color: #72767b;
  margin: 10px 0 -8px 10px;
}

.portalMain span {
  font-size: 14px;
  margin: 25px;
}
.portalMain >>> .el-divider {
  margin-top: 10px;
  width: 100%;
}
.claimDiv >>> .el-divider {
  margin: 10px;
  width: 90%;
}

.paperDiv1 {
  margin: -10px 20px;
  padding: 5px;
}
.paperDiv1 h4 {
  margin: 0;
}
.paperDiv1 >>> .el-divider {
  margin-top:40px;
}
.claimDiv2 {
  font-size: 14px;
  text-align: center;
  padding-top: 10px;
}
.claimDiv2 >>> .el-button {
  margin: 12px 0;
  width: 60%;
}
.el-icon-caret-top {
  position: fixed;
  right: 30px;
  bottom: 20px;
  width: 40px;
  height: 40px;
  background-color: #00a1d6;
  color: #00a1d6;
  border-radius: 50%;
}
.h4:hover {
  color: #1E90FF;
}
</style>